package com.gy.studyonlineapp.activity;

import static android.content.ContentValues.TAG;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gy.studyonlineapp.R;
import com.gy.studyonlineapp.callback.LoginAVQueryObserver;
import com.gy.studyonlineapp.common.Constants;
import com.gy.studyonlineapp.constants.LearnCloudClass;
import com.gy.studyonlineapp.constants.SharedPreference;
import com.gy.studyonlineapp.entity.User;

import java.io.IOException;
import java.util.concurrent.ConcurrentMap;

import cn.leancloud.AVOSCloud;
import cn.leancloud.AVObject;
import cn.leancloud.AVQuery;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    /*    NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        NavController navController = navHostFragment.getNavController();*/
        setContentView(R.layout.activity_login);
        //learnCloud初始化
        AVOSCloud.initialize(this,"VTYoQ9hAUCImRT2Cd6quVFDd-gzGzoHsz","WKStZ2bimcZLxz2izuy6OyDZ","https://vtyoq9ha.lc-cn-n1-shared.com");
        //删除标题栏
        if(getSupportActionBar()!=null){
            getSupportActionBar().hide();
        }
        EditText userName = this.findViewById(R.id.UserNameEdit);
        EditText password = this.findViewById(R.id.PassWordEdit);
        Button loginButton = this.findViewById(R.id.LoginButton);
        Button signUpButton = this.findViewById(R.id.SignUpButton);
        //登录按钮监听器
        loginButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if(userName != null && !userName.getText().toString().isEmpty()
                                && password != null && !password.getText().toString().isEmpty()){
                            String url = "http://" + Constants.localhost + ":8080/login";
                            OkHttpClient client = new OkHttpClient();
                            RequestBody requestBody = new FormBody.Builder()
                                    .add("username",userName.getText().toString())
                                    .add("password",password.getText().toString())
                                    .build();
                            Request request = new Request.Builder()
                                    .url(url)
                                    .post(requestBody)
                                    .build();
                            Call call = client.newCall(request);
                            call.enqueue(new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    System.out.println(e.getMessage() + "=============");
                                }
                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    String res = response.body().string();
                                    Log.d(TAG, "onResponse: "+ res);
                                    Gson gson = new Gson();
                                    if (res != null && !res.isEmpty())  {
                                        User user = gson.fromJson(res, User.class);
                                        System.out.println(user.getUsername() + "=============");
                                        if (user != null){
                                            SharedPreferences sp = getSharedPreferences(SharedPreference.SHARED, Context.MODE_PRIVATE);
                                            SharedPreferences.Editor spe = sp.edit();
                                            String userJson = gson.toJson(user);
                                            spe.putString("user",userJson);
                                            spe.putBoolean(SharedPreference.ISLOGIN,true);
                                            spe.commit();
                                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                        }else {
                                            Looper.prepare();
                                            Toast.makeText(LoginActivity.this, "用户名不存在!", Toast.LENGTH_SHORT).show();
                                            Looper.loop();
                                        }
                                    } else {
                                        Looper.prepare();
                                        Toast.makeText(LoginActivity.this, "用户名或密码错误!", Toast.LENGTH_SHORT).show();
                                        Looper.loop();
                                    }
                                }
                            });
                        } else {
                            Toast.makeText(LoginActivity.this,"请输入正确的用户名或密码!",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
        //注册按钮监听器
        signUpButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                    }
                }
        );
    }
}